package com.infitecs.eyas.security.service;

import com.infitecs.eyas.common.ajax.DataTablesPage;
import com.infitecs.eyas.security.dao.RoleDao;
import com.infitecs.eyas.security.model.Role;
import com.infitecs.eyas.security.model.User;
import com.infitecs.krill.autocomplete.service.AutoCompleteService;
import com.infitecs.krill.constant.Constant;
import com.infitecs.krill.exception.ValidateErrorException;
import com.infitecs.krill.mybatis.interceptor.PageInterceptor;
import com.infitecs.krill.mybatis.model.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AutoCompleteService autoCompleteService;

    public List<Role> getRoleList() {
        return roleDao.getRoleList();
    }

    public List<Role> getRoleListPage(Page dataTablesPage,Role role) {
        PageInterceptor.startPage(dataTablesPage);
        return roleDao.getRoleListPage(role);
    }

    public boolean addRole(Role role) {
        if (roleDao.getRoleByRoleName(role.getRoleName()) != null) {
            throw new ValidateErrorException("roleAlreadyExists");
        }
        roleDao.addRole(role);
        addUserRole(role);
        addRolePermission(role);
        autoCompleteService.initAutoComplete();
        return role.getRoleId() != null;
    }

    private void addUserRole(Role role) {
        if (role.getUserList() != null && !role.getUserList().isEmpty()) {
            roleDao.addUserRole(role);
        }
    }

    private void addRolePermission(Role role) {
        if (role.getPermTokenList() != null && !role.getPermTokenList().isEmpty()) {
            roleDao.addRolePermission(role);
        }
    }

    public boolean deleteRole(String roleId) {
        roleDao.deleteUserRoleByRoleId(roleId);
        roleDao.deleteRolePermissionByRoleId(roleId);
        boolean result = roleDao.deleteRole(roleId) == Constant.AFFECTED_LINE_1;
        autoCompleteService.initAutoComplete();
        return result;
    }

    public Role getRole(String roleId) {
        return roleDao.getRole(roleId);
    }

    public List<String> getUsernameByRoleId(String roleId) {
        return roleDao.getUsernameByRoleId(roleId);
    }

    public List<User> getUserByRoleId(String roleId) {
        return roleDao.getUserByRoleId(roleId);
    }

    public boolean updateRole(Role role) {
//        roleDao.deleteUserRoleByRoleId(role.getRoleId());
        addUserRole(role);
        roleDao.deleteRolePermissionByRoleId(role.getRoleId());
        addRolePermission(role);
        boolean result = roleDao.updateRole(role) == Constant.AFFECTED_LINE_1;
        autoCompleteService.initAutoComplete();
        return result;
    }
}
